#encoding=utf8
'''
Created on Oct 22, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
import threading

from django.core.mail.message import EmailMessage
from django.utils import timezone
from django.core.mail import mail_admins

import gspread
from gspread.exceptions import CellNotFound

import settings
import json
import utils


class EmailThread(threading.Thread):
    def __init__(self, subject, sender, content, to):
        self.subject = subject
        self.sender = sender
        self.to = to
        self.content = content
        threading.Thread.__init__(self)

    def run(self):
        msg = EmailMessage(self.subject, self.content, self.sender,
            self.to)
        msg.content_subtype = 'html'
        msg.send()
        print 'email sent!'


def _append_row(wks, data_list):
    try:
        wks.append_row(data_list)
        return True
    except Exception, e:
        print e
        return False


class UpdateGoogleSheetThread(threading.Thread):

    def __init__(self, file_name, data_list):
        self.file_name = file_name
        self.data_list = data_list
        threading.Thread.__init__(self)

    def run(self):
        for i in range(5):
            try:
                gc = gspread.login(settings.WRITER_EMAIL, settings.WRITER_PWD)
                wks = gc.open(self.file_name).sheet1
                if not _append_row(wks, self.data_list):
                    print 'Try again...'
                    continue
                print 'updated!'
                return
            except Exception, e:
                print e
                continue
        mail_admins('Update Google Sheet Failed.',
            'update google sheet: %s failed. (%s)' %\
            (self.file_name, self.data_list[0]), True)


class RegisterAPMThread(threading.Thread):

    def __init__(self, sub_info):
        self.sub_info = sub_info
        super(RegisterAPMThread, self).__init__()

    def run(self):
        results = []
        app = self.sub_info.app
        ctx = {'product_id': app.prd_id, 'app_code': app.prj_code,
               'alt_app_code': app.old_prj_code, 'app_name': app.app_name,
               'pub_app_name': app.pub_name, 'bundle_id_prefix': app.bundle_id_prefix,
               'bundle_id_suffix': app.bundle_id_suffix,
               'full_bundle_id': app.get_full_bundle_id(),
               'platform': app.get_platform_display(), 'app_store': app.app_store,
               'apple_id': app.app_id, 'store_link': app.store_link,
               'publish_studio': '%s - %s' % (app.studio.custom_id, app.studio.pub_name),
               'studio_cloud': app.studio.cloud.cloud_id,
               'initial_release_date': str(app.get_initial_release_date()),
               'flurry_key': app.flurry_key, 'division': app.get_division(),
               'team': app.get_team()}
        v = app.appversion_set.filter(code=self.sub_info.version, status='L')[:1]
        v = v[0] if v else None
        versions = [{'task_id': v.log_id,
                     'coordinator': v.get_coordinator(),
                     'version_num': v.code,
                     'release_date': str(v.date_released) or "",
                     'release_notes': v.change_list,
                     'has_iap': True if v.iap_required == 'Y' else False,
                     'has_ads': True if v.ads_required == 'Y' else False,
                     'has_cross_promo': True if v.cross_promo_required == 'Y' else False}] if v else []
        ctx.update({'versions': versions})
        results.append(ctx)
        data = {'results': results}
        rtn = utils.api_call('%s%s' % (settings.APM_DOMAIN, settings.APM_NEW_RELEASED),
            json.dumps(data), 'POST', {'Content-Type': 'application/json'})
        print rtn
        if not rtn.get('status', '').lower() == 'ok':
            mail_admins('Register APM Failed.', 'Register app: %s to APM failed, %s' %\
                rtn.get('msg'), True)


#class UpdateGoogleSheetThread(threading.Thread):
#    def __init__(self, obj, ads_obj=None):
#        self.obj = obj
#        self.ads_obj = ads_obj
#        threading.Thread.__init__(self)
#
#    def run(self):
#        gc = gspread.login(settings.WRITER_EMAIL, settings.WRITER_PWD)
#        wks = gc.open(settings.FILE_NAME).sheet1
#        data_list = [timezone.localtime(self.obj.create_time).strftime('%Y-%m-%d %H:%M:%S'),
#            self.obj.editor, self.obj.prj_code, self.obj.app_name, self.obj.app_store,
#            self.obj.studio.pub_name, self.obj.old_prj_code, self.obj.get_platform_display(),
#            self.obj.get_full_bundle_id()]
#        if self.ads_obj:
#            data_list += [self.ads_obj.get_orientation_display(),
#                          self.ads_obj.space, self.ads_obj.notes,
#                          self.ads_obj.get_cross_promo_display(),
#                          self.ads_obj.cross_link]
#        wks.append_row(data_list)
#        print 'updated!'
